package com.shangyueshang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shangyueshang.common.SysConstants;
import com.shangyueshang.mapper.GoodsMapper;
import com.shangyueshang.mapper.GoodsStorageFeeMapper;
import com.shangyueshang.model.Goods;
import com.shangyueshang.model.GoodsStorageFee;
import com.shangyueshang.request.GoodsDTO;
import com.shangyueshang.request.PageReq;
import com.shangyueshang.response.HttpResult;
import com.shangyueshang.response.PageResult;
import com.shangyueshang.response.ShopSkuDTO;
import com.shangyueshang.service.GoodsService;
import com.shangyueshang.thread.ExecutorType;
import com.shangyueshang.utils.CollectionUtil;
import com.shangyueshang.utils.MyPageHelper;
import com.shangyueshang.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/1/14 15:16
 * @version: v1.0.0
 */
@Slf4j
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
	
	@Resource(name = ExecutorType.defaultExecutor)
	private Executor myExecutor;
	
	@Resource
	private GoodsStorageFeeMapper goodsStorageFeeMapper;
	
	@Override
	public HttpResult<Void> save(GoodsDTO goodsDTO) {
		Goods nGoods = new Goods();
		Goods goods = super.getById(goodsDTO.getId());
		if (Objects.isNull(goods)) {
			nGoods.setCreator(SecurityUtil.getUsername());
			nGoods.setCreateTime(LocalDateTime.now());
		}
		nGoods.setLastUpdator(SecurityUtil.getUsername());
		nGoods.setLastUpdateTime(LocalDateTime.now());
		BeanUtils.copyProperties(goodsDTO, nGoods);
		try {
			super.saveOrUpdate(nGoods);
		} catch (DuplicateKeyException e) {
			log.error("save goods error:{}", e.getMessage());
			return HttpResult.fail("sku或fn_sku已存在");
		}
		//去补充goods_storage_fee表sku字段为空的数据
		myExecutor.execute(
				() -> {
					List<GoodsStorageFee> goodsStorageFeeList = goodsStorageFeeMapper.selectList(
							new QueryWrapper<GoodsStorageFee>()
									.eq(SysConstants.asin, nGoods.getAsin())
									.eq(SysConstants.shop, nGoods.getShop())
									.isNull(SysConstants.sku)
									.select(SysConstants.id)
					);
					if (!CollectionUtil.isEmpty(goodsStorageFeeList)) {
						goodsStorageFeeList.forEach(
								i -> {
									i.setSku(nGoods.getSku());
									goodsStorageFeeMapper.updateById(i);
								}
						);
						log.warn("filled with goods_storage_fee sku is {}", nGoods.getSku());
					}
				}
		);
		return HttpResult.ok();
	}
	
	@Override
	public PageResult<Goods> findPage(PageReq pageReq) {
		QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc(SysConstants.create_time);
		Map<String, Object> queryParams = pageReq.getLineParams();
		queryWrapper.in(SysConstants.shop, (List) queryParams.remove(SysConstants.shop));
		queryParams.forEach(
				(k, v) -> {
					switch (k) {
						case SysConstants.sku:
						case SysConstants.name:
							queryWrapper.like(k, v);
							break;
						default:
							queryWrapper.eq(k, v);
							break;
					}
				}
		);
		PageInfo<Goods> pageInfo =
				PageHelper.startPage(
						pageReq.getPageNum(),
						pageReq.getPageSize()
				).doSelectPageInfo(
						() -> super.list(queryWrapper)
				);
		return MyPageHelper.getPageResult(pageInfo);
	}
	
	@Override
	public Map<String, ShopSkuDTO> queryByShop(String shop) {
		List<ShopSkuDTO> list = getBaseMapper().queryByShop(shop);
		return list.stream().collect(Collectors.toMap(ShopSkuDTO::shopSkuKey, Function.identity()));
	}
}
